package com.why.catchMsg.service.impl;

import com.why.catchMsg.util.ApplicationContextUtils;
import com.why.catchMsg.service.CacheService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;

@Service
@Slf4j
@Setter
public class ECacheServiceImpl implements CacheService{

    @Value("sessionCache")
    private String cacheName;

    @Override
    public void putCode(String key, String value) {
        EhCacheCacheManager cacheCacheManager= ApplicationContextUtils.applicationContext.getBean(EhCacheCacheManager.class);
        //获取CacheManager类
        CacheManager cacheManager=cacheCacheManager.getCacheManager();
        //获取Cache
        Cache cache=cacheManager.getCache(this.cacheName);
        cache.put(new Element(key,value));
    }

    @Override
    public Object getCode(String key) {
        EhCacheCacheManager cacheCacheManager= ApplicationContextUtils.applicationContext.getBean(EhCacheCacheManager.class);
        //获取CacheManager类
        CacheManager cacheManager=cacheCacheManager.getCacheManager();
        //获取Cache
        Cache cache=cacheManager.getCache(this.cacheName);
        if(cache.get(key)==null){
            return  null;
        }
        return cache.get(key).getObjectValue();
    }

    @Override
    public String getSessionId()  {
        String sessionId= String.valueOf(getCode("session_id"));
        log.info("sessionId:{}",sessionId);

        return sessionId;
    }


}
